package com.example.threadpool.task;

import com.example.ioc.annotation.AutoWired;
import com.example.ioc.annotation.Component;
import com.example.threadpool.config.ThreadPoolConfig;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class TimeTask {

    @AutoWired
    private ThreadPoolConfig threadPoolConfig;

    private ThreadPoolExecutor executor;

    public void startTasks() {
        // 获取线程池实例
        executor = threadPoolConfig.createThreadPool();

        // 提交每秒输出时间的任务
        executor.submit(this::printTimeEverySecond);

        // 提交倒计时1分钟的任务
        executor.submit(() -> countDownFromOneMinute(60));
    }

    // 每秒输出一次当前时间
    private void printTimeEverySecond() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 运行10次后停止
            for (int i = 0; i < 10; i++) {
                Date now = new Date();
                System.out.println("当前时间: " + sdf.format(now));
                Thread.sleep(1000);
            }
            System.out.println("时间输出任务完成");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("时间输出任务被中断");
        }
    }

    // 从指定秒数开始倒计时
    private void countDownFromOneMinute(int seconds) {
        try {
            for (int i = seconds; i > 0; i--) {
                System.out.println("倒计时: " + i + " 秒");
                Thread.sleep(1000);
            }
            System.out.println("倒计时结束!");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("倒计时任务被中断");
        }
    }

    // 关闭线程池
    public void shutdown() {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
            System.out.println("线程池已关闭");
        }
    }
}
